<template>
	<view class="container">
		<!-- 顶部蓝色渐变背景 -->
		<view class="me-gradient-bg">
			<view class="user-info-row">
				<!-- 左侧：头像、昵称、签名 -->
				<view class="user-info-left" @click="handleLogin">
					<image class="avatar-row" :src="avatarUrl"></image>
					<view class="user-text-col">
						<view class="user-name">{{ userInfo.nickname || (isLoggedIn ? 'User' : '登录/注册') }}</view>
						<view class="user-desc">{{ userInfo.signature || '这个人很神秘，什么都没有写' }}</view>
					</view>
				</view>
				<!-- 右侧：设置按钮 -->
				<view class="user-info-right">
					<u-icon name="setting" color="#fff" size="36" @click="handleSetting" />
				</view>
			</view>
		</view>
		<!-- 余额和卡券蓝色卡片，悬浮在渐变色上 -->
		<view class="balance-card-gradient me-balance-float">
			<view class="balance-card-content">
				<view class="balance-item" @click="handleBalance">
					<view class="icon">
						<u-icon name="rmb-circle" color="#fff" size="40"></u-icon>
					</view>
					<view class="amount white">{{ isLoggedIn ? Number(userInfo.money).toFixed(2) : '0.00' }}</view>
					<view class="label white-label">可用余额</view>
				</view>
				<view class="divider-vertical"></view>
				<view class="balance-item" @click="goToCoupons">
					<view class="icon">
						<u-icon name="coupon" color="#fff" size="40"></u-icon>
					</view>
					<view class="amount white">{{ userInfo.user_coupon_count || 0 }}</view>
					<view class="label white-label">我的卡券</view>
				</view>
			</view>
		</view>
		<!-- 轮播图 - 与首页样式和功能对齐 -->
		<view class="banner-center-container">
			<swiper
				v-if="bannerList && bannerList.length > 0"
				class="banner-swiper"
				circular
				:indicator-dots="true"
				:autoplay="true"
				interval="3000"
				duration="1000"
				indicator-color="rgba(255, 255, 255, 0.6)"
				indicator-active-color="#ffffff"
			>
				<swiper-item v-for="(bannerItem, index) in bannerList" :key="index" @click="handleBannerClick(bannerItem)">
					<view class="banner-item">
						<image :src="globalConfig.site_url + bannerItem.image" mode="aspectFill" class="swiper-img" @error="handleImageError"></image>
					</view>
				</swiper-item>
			</swiper>
			<view v-else class="banner-placeholder">
				<text>暂无轮播图数据</text>
			</view>
		</view>

		<!-- 功能菜单区域 -->
		<view class="menu-grid" v-if="menuItems && menuItems.length > 0">
			<view  class="menu-item" v-for="(item, index) in menuItems" :key="index" @click="handleMenuClick(item)">
				<button class='content cu-btn' v-if="item.show_data === '3'" open-type="contact"
					style="height: auto;background: none; border: 0 !important; padding: 0; display: flex; flex-direction: column; align-items: center; width: 100%;">
					<image :src="item.image" mode="aspectFit" class="menu-icon"></image>
					<text class="menu-text">{{ item.name }}</text>
				</button>
			<template v-else>
				<image :src="item.image" mode="aspectFit" class="menu-icon" @click="handleMenuClick(item)"></image>
				<text class="menu-text" @click="handleMenuClick(item)">{{ item.name }}</text>
			</template>
			</view>
		</view>

		<!-- uView登录弹窗 -->
		<u-popup v-model="showLoginPopup" mode="center" border-radius="16" width="600rpx" :mask-close-able="true" @close="closeLoginPopup">
			<view class="login-popup">
				<view class="popup-header">
					<view class="popup-title">登录</view>
					<view class="popup-close" @click="closeLoginPopup">
						<u-icon name="close" color="#999" size="20"></u-icon>
					</view>
				</view>

				<view class="login-methods">
					<u-button type="success" shape="round" :loading="wechatLoading" @click="handleWechatLogin" :custom-style="wechatBtnStyle">
						<u-icon name="weixin-fill" color="#fff" size="20" style="margin-right: 10rpx"></u-icon>
						{{ wechatLoading ? '登录中...' : '微信一键登录' }}
					</u-button>

					<!-- <u-button 
            type="primary" 
            shape="round" 
            plain
            @click="handlePhoneLogin"
            :custom-style="phoneBtnStyle"
          >
            <u-icon name="phone" color="#0066ff" size="20" style="margin-right: 10rpx;"></u-icon>
            手机号登录
          </u-button> -->
				</view>

				<view class="login-tips">
					<u-checkbox v-model="agreePolicy" shape="circle" active-color="#007aff" :size="32" style="margin-right: 10rpx;" />
					<text class="tips-text">我已阅读并同意</text>
					<text class="link-text" @click="showPrivacy('agreement')">《用户协议》</text>
					<text class="tips-text">和</text>
					<text class="link-text" @click="showPrivacy('policy')">《隐私政策》</text>
				</view>
			</view>
		</u-popup>

		<!-- 加载提示 -->
		<u-loading-page :loading="pageLoading" loading-text="加载中..." bg-color="#f5f5f5"></u-loading-page>
	</view>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { checkLoginStatus, getUserInfo, wechatMiniLogin, fetchUserInfo, fetchUserBalance, fetchUserVouchers, logout } from '@/common/auth.js';

export default {
	computed: {
		...mapState({
			userInfo: (state) => state.userInfo,
			globalConfig: (state) => state.config
		}),
		isLoggedIn() {
			// 登录状态直接和全局的userInfo绑定，更可靠
			return this.userInfo && this.userInfo.id;
		},
		avatarUrl() {
			if (!this.userInfo || !this.userInfo.image) {
				return '/static/me/icon/touxiang.png'; // 默认头像
			}
			const avatar = this.userInfo.image;
			// 如果已经是完整的URL，直接返回
			if (avatar.startsWith('http') || avatar.startsWith('//')) {
				return avatar;
			}
			// 如果是相对路径，并且全局配置已加载，则拼接
			if (this.globalConfig && this.globalConfig.site_url) {
				return this.globalConfig.site_url + avatar;
			}
			// 降级处理，返回默认头像
			return '/static/me/icon/touxiang.png';
		}
	},
	data() {
		return {
			showLoginPopup: false,
			pageLoading: false,
			wechatLoading: false,
			balance: 0,
			vouchers: 0,
			menuItems: [],
			agreePolicy: false,
			wechatBtnStyle: {
				backgroundColor: '#07c160',
				borderColor: '#07c160',
				marginBottom: '20rpx'
			},
			phoneBtnStyle: {
				borderColor: '#0066ff',
				color: '#0066ff'
			},
			bannerList: [],
			toolsList: []
		};
	},
	created() {
		this.refreshUserData();
	},

	methods: {
		...mapActions(['fetchUserInfoAction', 'fetchConfig']),

		async refreshUserData() {
			// 确保全局配置已加载
			if (!this.globalConfig || !this.globalConfig.site_url) {
				try {
					await this.fetchConfig();
				} catch (error) {
					this.$u.toast('加载全局配置失败，请稍后重试');
					return;
				}
			}

			const isLoggedIn = await checkLoginStatus();
			if (isLoggedIn) {
				this.pageLoading = true;
				try {
					const pageData = await this.fetchUserInfoAction();
					console.log(pageData, 'pageData');
					console.log(this.globalConfig, 'this.globalConfig');

					if (pageData) {
						this.bannerList = pageData.banner_list || [];
						this.menuItems = pageData.tools_list || [];
						this.menuItems.forEach((item) => {
							item.image = this.globalConfig.site_url + item.image;
						});
						console.log(this.menuItems, 'menuItems');
					}
				} catch (error) {
					console.error('刷新用户信息失败:', error);
					this.$u.toast('用户信息更新失败');
				} finally {
					this.pageLoading = false;
				}
			}
		},

		handleLogin() {
			if (!this.isLoggedIn) {
				this.showLoginPopup = true;
			} else {
				// 如果已登录，点击头像可以跳转到编辑页
				uni.navigateTo({
					url: '/pages/user/profile'
				});
			}
		},

		// 关闭登录弹窗
		closeLoginPopup() {
			this.showLoginPopup = false;
			this.wechatLoading = false;
		},

		// 微信登录
		async handleWechatLogin() {
			if (this.wechatLoading) return;
			if (!this.agreePolicy) {
				this.$u.toast('请先勾选同意《用户协议》和《隐私政策》');
				return;
			}
			this.wechatLoading = true;
			try {
				const result = await wechatMiniLogin();
				if (result.success) {
					this.closeLoginPopup();
					this.$u.toast('登录成功');
					// Refresh all user-dependent data on the page
					this.refreshUserData();
				} else {
					throw new Error(result.message || '登录失败');
				}
			} catch (error) {
				console.error('微信登录失败:', error);
				this.$u.toast(error.message || '登录失败');
			} finally {
				this.wechatLoading = false;
			}
		},

		// 手机号登录
		handlePhoneLogin() {
			this.closeLoginPopup();
			uni.navigateTo({
				url: '/pages/login/phone'
			});
		},

		// 显示隐私政策
		showPrivacy(type) {
			const urlKey = type === 'policy' ? 'yszc_url' : 'yhxy_url';
			const title = type === 'policy' ? '隐私政策' : '用户协议';
			if (this.globalConfig && this.globalConfig[urlKey]) {
				uni.navigateTo({
					url: `/pages/common/webview?url=${encodeURIComponent(this.globalConfig[urlKey])}&title=${encodeURIComponent(title)}`
				});
			} else {
				this.$u.toast('协议地址未配置');
			}
		},

		// 功能菜单点击
		handleMenuClick(item) {
			if (!item.show_data) {
				// 兼容旧数据或异常数据
				this.$u.toast('功能配置错误，请联系管理员');
				return;
			}

			// 根据 show_data 执行不同操作
			switch (item.show_data) {
				case '1': // 内部页面跳转
					if (!item.pages.url) {
						this.$u.toast('页面地址未配置');
						return;
					}
					uni.navigateTo({
						url: item.pages.url, // Use item.pages for the URL
						fail: () => {
							this.$u.toast('页面跳转失败，请检查路径');
						}
					});
					break;
				case '2': // 跳转到外部H5
					if (!item.url) {
						this.$u.toast('外部链接未配置');
						return;
					}
					uni.navigateTo({
						url: `/pages/common/webview?url=${encodeURIComponent(item.url)}`
					});
					break;
				case '3': // 联系客服
					// 使用微信小程序原生客服功能
					// 由于无法直接触发 open-type="contact"，这里显示提示
					uni.showToast({
						title: '请点击右上角菜单选择"联系客服"',
						icon: 'none',
						duration: 3000
					});
					break;
				case '4': // 富文本内容
					if (item.content) {
						const title = item.name || '详情';
						uni.navigateTo({
							url: `/pages/common/rich-text?title=${encodeURIComponent(title)}&content=${encodeURIComponent(item.content)}`
						});
					}
					break;
				default:
					this.$u.toast('未知操作类型');
					break;
			}
		},

		// 处理余额点击
		handleBalance() {
			if (!this.isLoggedIn) {
				this.handleLogin();
				return;
			}

			uni.navigateTo({
				url: '/pages/wallet/recharge',
				fail: () => {
					this.$u.toast('余额功能开发中');
				}
			});
		},

		// 处理卡券点击
		goToCoupons() {
			if (!this.isLoggedIn) {
				this.handleLogin();
				return;
			}

			uni.navigateTo({
				url: '/pages/user/coupons'
			});
		},

		// 处理消息点击
		handleMessage() {
			if (!this.isLoggedIn) {
				this.handleLogin();
				return;
			}

			uni.navigateTo({
				url: '/pages/message/center',
				fail: () => {
					this.$u.toast('消息功能开发中');
				}
			});
		},

		// 处理设置点击
		handleSetting() {
			if (!this.isLoggedIn) {
				this.handleLogin();
				return;
			}

			uni.navigateTo({
				url: '/pages/user/profile',
				fail: () => {
					this.$u.toast('设置功能开发中');
				}
			});
		},

		// 返回
		goBack() {
			uni.navigateBack({
				delta: 1,
				fail: () => {
					uni.switchTab({
						url: '/pages/index/index'
					});
				}
			});
		},

		handleBannerClick(item) {
			if (!item) return;
			const showData = item.show_data || item.type_data;
			if (showData == '1') {
				// 内部页面跳转
				const url = (item.pages && item.pages.url) || item.url;
				if (url) {
					uni.navigateTo({
						url
					});
				} else {
					// this.$u.toast('页面地址未配置');
				}
			} else if (showData == '2') {
				// 外部H5
				if (item.url) {
					uni.navigateTo({
						url: `/pages/common/webview?url=${encodeURIComponent(item.url)}`
					});
				} else {
					// this.$u.toast('外部链接未配置');
				}
			} else {
				// this.$u.toast('未配置跳转类型');
			}
		},

		handleImageError(e) {
			// 处理图片加载失败
		},

		handleToolClick(item) {
			if (!item || !item.type || !item.url) {
				this.$u.toast('功能配置错误');
				return;
			}

			if (item.type == 1) {
				// 内部页面跳转
				uni.navigateTo({
					url: item.url,
					fail: () => {
						this.$u.toast('页面跳转失败，请检查路径');
					}
				});
			} else if (item.type == 2) {
				// 外部链接，先复制到剪贴板提示用户
				uni.setClipboardData({
					data: item.url,
					success: () => {
						this.$u.toast('链接已复制，请在浏览器中打开');
					}
				});
			} else {
				this.$u.toast('未知操作类型');
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: #f5f5f5;
}

.safe-area-bg {
	height: var(--status-bar-height, 44px);
	background: linear-gradient(to right, #2176ff, #33aaff);
}

.user-row {
	display: flex;
	align-items: center;
	padding: 0 30rpx 0 30rpx;
	margin-top: -40rpx;
	margin-bottom: 10rpx;
}

.avatar-side {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	border: 4rpx solid #fff;
	background-color: #f0f0f0;
	margin-right: 24rpx;
}

.user-info-text {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

.user-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #222;
}

.user-desc {
	font-size: 26rpx;
	color: #f0f0f0;
	opacity: 0.85;
	margin-top: 6rpx;
}

.user-icons {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	justify-content: center;
	gap: 18rpx;
}

.top-icon {
	margin-bottom: 0;
}

.balance-card-gradient {
	margin: 30rpx 20rpx 0 20rpx;
	border-radius: 24rpx;
	background: linear-gradient(90deg, #2176ff 0%, #33aaff 100%);
	box-shadow: 0 4rpx 24rpx rgba(33, 118, 255, 0.1);
	padding: 0;
}

.balance-card-content {
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
	padding: 40rpx 0;
}

.balance-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.icon {
	margin-bottom: 10rpx;
}

.amount.white {
	color: #fff;
	font-size: 44rpx;
	font-weight: bold;
	margin: 10rpx 0 0 0;
}

.label.white-label {
	color: rgba(255, 255, 255, 0.85);
	font-size: 28rpx;
	margin-top: 8rpx;
}

.divider-vertical {
	width: 2rpx;
	height: 80rpx;
	background: rgba(255, 255, 255, 0.18);
	border-radius: 2rpx;
}

.menu-grid {
	background-color: #fff;
	margin: 20rpx;
	border-radius: 16rpx;
	padding: 20rpx;
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 20rpx;

	.menu-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx 0;

		.menu-icon {
			width: 68rpx;
			height: 68rpx;
			margin-bottom: 12rpx;
		}

		.menu-text {
			font-size: 24rpx;
			color: #333;
			text-align: center;
		}
	}
}

.login-popup {
	padding: 40rpx;

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 40rpx;

		.popup-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		.popup-close {
			padding: 10rpx;
		}
	}

	.login-methods {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		margin-bottom: 40rpx;
	}

	.login-tips {
		font-size: 24rpx;
		color: #999;
		text-align: center;
		margin-top: 40rpx;
		/* 与按钮拉开距离 */
	}

	.login-tips .link-text {
		color: #007aff;
		margin: 0 4rpx;
	}
}

.my-coupon-entry {
	display: flex;
	align-items: center;
	background: #fff;
	border-radius: 16rpx;
	margin: 32rpx 24rpx 0 24rpx;
	padding: 24rpx 24rpx;
	box-shadow: 0 2rpx 12rpx rgba(90, 156, 248, 0.06);

	.coupon-label {
		font-size: 32rpx;
		color: #2468f2;
		margin-left: 16rpx;
		font-weight: bold;
	}

	.coupon-count {
		margin-left: 16rpx;
		background: #2468f2;
		color: #fff;
		border-radius: 24rpx;
		padding: 0 18rpx;
		font-size: 28rpx;
		font-weight: bold;
	}

	.u-icon {
		margin-left: auto;
	}
}

/* 与首页对齐的轮播图样式 */
.banner-center-container {
	height: 320rpx;
	min-height: 320rpx;
	margin: 20rpx;
	position: relative;
	z-index: 1;
	background: #f5f6fa;
	border-radius: 16rpx;
	overflow: hidden;
	display: flex;
	align-items: center;
	justify-content: center;
}

.banner-center-container .banner-swiper,
.banner-center-container .banner-item,
.banner-center-container .swiper-img {
	width: 100%;
	height: 100%;
	border-radius: 16rpx;
}

.banner-center-container .banner-placeholder {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #f5f6fa;
	border-radius: 16rpx;
	color: #999;
	font-size: 28rpx;
}

.brand-header {
	display: flex;
	align-items: center;
	padding: 20rpx 30rpx;
	background-color: #fff;
	padding-top: 118rpx;

	.brand-icon {
		width: 80rpx;
		height: 30rpx;
		font-size: 36rpx;
		font-weight: bold;
	}

	.brand-subtitle {
		font-size: 24rpx;
		color: #666;
		margin-left: 20rpx;
		padding: 4rpx 12rpx;
		background-color: #f5f5f5;
		border-radius: 20rpx;
	}

	.header-right {
		margin-left: auto;

		.iconfont {
			margin-left: 30rpx;
			font-size: 40rpx;
		}
	}
}

.me-gradient-bg {
	width: 100%;
	background: linear-gradient(180deg, #2176ff 0%, #6ecbff 100%);
	position: relative;
	z-index: 1;
	padding: var(--status-bar-height) 0 80rpx 0;
	box-sizing: border-box;
	padding-top: 118rpx;
}

.user-info-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 30rpx 0 30rpx;
}

.user-info-left {
	display: flex;
	align-items: center;
	flex: 1;
}

.avatar-row {
	width: 110rpx;
	height: 110rpx;
	border-radius: 50%;
	border: 4rpx solid #fff;
	margin-right: 20rpx;
}

.user-text-col {
	display: flex;
	flex-direction: column;
}

.user-name {
	color: #fff;
	font-size: 34rpx;
	font-weight: bold;
}

.user-desc {
	color: rgba(255, 255, 255, 0.85);
	font-size: 26rpx;
	margin-top: 8rpx;
}

.user-info-right {
	display: flex;
	align-items: center;
}

.me-balance-float {
	margin-top: -60rpx;
	z-index: 2;
	position: relative;
}

.common-tools {
	padding: 32rpx 0;
	background-color: #ffffff;
	border-radius: 16rpx;
	margin: 24rpx;

	.tool-title {
		padding-left: 24rpx;
		font-size: 32rpx;
		color: #333;
		margin-bottom: 24rpx;
		font-weight: bold;
	}

	.tool-scroll {
		width: 100%;
		white-space: nowrap;
		box-sizing: border-box;
		padding-left: 24rpx;
	}

	.tool-item {
		display: inline-flex;
		flex-direction: column;
		align-items: center;
		width: 160rpx;
		margin-right: 20rpx;
		font-size: 24rpx;
		color: #666;

		.tool-icon {
			width: 88rpx;
			height: 88rpx;
			margin-bottom: 12rpx;
		}

		.tool-name {
			// Styles from parent are sufficient
		}
	}
}

:deep.wx-button:after{
	border: 0 !important;
}
</style>
